const path = require('path')
const fs = require('fs')

module.exports = class TestNow {

	genJestSource(sourcePath = path.resolve('./')) {
		// 准备环境
		const testPath = `${sourcePath}/__test__`
		if (fs.existsSync(testPath)) {
			// 删除测试文件夹
			fs.rmdirSync(testPath, {
				recursive: true
			})
		}
		fs.mkdirSync(testPath)
		// 遍历代码文件
		let list = fs.readdirSync(sourcePath)
		list
			// 添加完整路径 
			.map(v => path.join(sourcePath, v))
			// 过滤文件
			.filter(v => fs.statSync(v).isFile())
			// 排除测试代码
			.filter(v => v.indexOf('.spec') === -1)
			.map(v => this.genTestFile(v))

	}
	genTestFile(filename) {
		const testFileName = this.getTestFileNmae(filename)
		console.log(testFileName);
		if (fs.existsSync(testFileName)) {
			console.log('测试代码文件已存在');
			return
		}
		const mod = require(filename)
		let source
		if (typeof mod === 'object') {
			source = Object.keys(mod)
				.map(v => this.getTestSource(v, path.basename(filename), true))
				.join('\n')
		} else if (typeof mod === 'function') {
			const basename = path.basename(filename)
			source = this.getTestSource(basename.replace('.js', ''), basename)
		}
		fs.writeFileSync(testFileName, source)
	}
	getTestSource(methodName, classFile, isClass = false) {
		return `test('${'Test ' + methodName}',()=>{
					const ${isClass ? '{' + methodName + '}' : methodName} = require('${'../' + classFile}')
					const ret = ${methodName}()
					// expect(ret).toBe('test return')
				})`
	}

	/**
	 * 生成方法名
	 * @param {*} fileName 代码文件名
	 */
	getTestFileNmae(fileName) {
		const diename = path.dirname(fileName)
		const baseName = path.basename(fileName)
		const extName = path.extname(fileName)
		const testName = baseName.replace(extName, `.spec${extName}`)
		return path.format({
			root: diename + '/__test__/',
			base: testName
		})
	}
}
